package io.gitee.kotle.android.mvvm

import android.content.res.Configuration
import android.content.res.Resources
import android.os.Bundle
import android.view.*
import androidx.activity.OnBackPressedCallback
import androidx.core.view.MenuProvider
import androidx.fragment.app.Fragment
import io.gitee.kotle.android.delegate.unsafeLazy
import io.gitee.kotle.android.mvvm.mvvminterface.IBaseMvvm
import io.gitee.kotle.android.mvvm.mvvminterface.ScreenOrientationHelper
import io.gitee.kotle.android.utils.appCompatActivity

/**
 * 所有fragment的基类
 */
abstract class MvvmFragment : Fragment(), IBaseMvvm, MenuProvider {
    private val screenOrientationHelper by unsafeLazy { ScreenOrientationHelper(this) }

    /**
     * 是否需要菜单
     */
    open fun isNeedMenuProvider() = false

    /**
     * onCreateView
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return onHandleCreateMvvmViewType(layoutInflater, container, savedInstanceState)
    }

    /**
     * onViewCreated
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //是否需要菜单
        if (isNeedMenuProvider()) {
            appCompatActivity.addMenuProvider(this, viewLifecycleOwner)
        }
        //返回键监听
        onBackPressed()?.let {
            appCompatActivity.onBackPressedDispatcher.addCallback(viewLifecycleOwner, it)
        }
        //view创建完成
        onViewCreatedFinish(this, savedInstanceState, resources)
    }

    /**
     * 监听返回按键
     */
    open fun onBackPressed(): OnBackPressedCallback? =
        null

    /**
     * 一个简单的OnBackPressedCallback对象
     */
    inline fun backPressed(crossinline listener: Function0<Unit>) =
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                listener.invoke()
            }
        }

    /**
     * 通常和viewPager搭配
     */
    open fun getTitle(): CharSequence? {
        return activity?.title
    }

    /**
     * 设置title
     */
    open fun setTitle(text: CharSequence) {
        activity?.title = text
    }

    /**
     * 设置title
     */
    open fun setTitle(text: Int) {
        activity?.setTitle(text)
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        checkScreenPortrait(resources)
    }

    final override fun checkScreenPortrait(resources: Resources) {
        screenOrientationHelper.checkScreenPortrait(resources)
    }

    override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {

    }

    override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        return false
    }

    override fun onPrepareMenu(menu: Menu) {
    }

    override fun onMenuClosed(menu: Menu) {

    }
}